<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { ArrowRight } from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import BottomNavigation from "@/components/ChatComponents/BottomNavigation.vue";
// 定义User接口
interface User {
  id: number;
  username: string;
  wechat_number: string;
  avatar: string;
}

// 初始化用户数据（指定User类型）
const userList = ref<User>({} as User);
const router = useRouter();
const isLoaded = ref(false); // 标记数据是否加载完成

// 工具函数：从Token中解析出用户ID，这里假设Token是JWT格式，从payload里取sub（也可根据实际Token结构调整）
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; // 假设用户ID存放在JWT的sub字段，实际根据后端生成Token逻辑调整
  } catch (error) {
    console.error('解析Token失败:', error);
    return '';
  }
};

// 接口请求获取用户信息
onMounted(() => {
  const token = localStorage.getItem('token'); // 从localStorage中获取登录时存储的Token
  if (!token) {
    ElMessage.warning('未检测到登录态，请先登录');
    return;
  }
  const userId = getUserIdFromToken(token);
  if (!userId) {
    ElMessage.warning('Token解析失败或无效，无法获取用户ID');
    return;
  }
  axios.get('http://localhost:8020/user/GetUserInfo', {
    params: {
      userId: userId // 使用解析出来的用户ID
    }
  })
      .then(res => {
        // 验证接口返回结构是否正确
        if (res.data && res.data.id) {
          userList.value = res.data;
          isLoaded.value = true;
          console.log('用户数据加载成功：', userList.value);
        } else {
          ElMessage.warning('接口返回格式不正确，缺少id字段');
        }
      })
      .catch(err => {
        ElMessage.error('请求失败！请检查网络或接口地址');
        console.error('错误详情：', err);
      });
});

// 监听id变化，确保路由参数有效
watch(
    () => userList.value.id,
    (newId) => {
      if (!newId && isLoaded.value) {
        ElMessage.warning('用户ID不存在，无法跳转');
      }
    }
);

// 退出登录逻辑
const handleLogout = () => {
  ElMessageBox.confirm(
      '确定要退出登录吗？',
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => {
        // 1. 清除本地存储的token
        localStorage.removeItem('token');
        // 2. 跳转到登录页
        router.push({ name: 'Register' });
        ElMessage.success('退出登录成功');
      })
      .catch(() => {
        ElMessage.info('已取消退出');
      });
};

// 注销账号逻辑
const write = () => {
  // 1. 先校验登录态和用户ID
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未检测到登录态，无法注销');
    return;
  }
  const userId = getUserIdFromToken(token);
  if (!userId) {
    ElMessage.warning('Token解析失败，无法获取用户ID');
    return;
  }
  ElMessageBox.confirm(
      '确定要注销账号吗？',
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => {
        // 3. 调用后端删除接口
        return axios.delete('http://localhost:8020/user/deleteUser', {
          params: { userId: userId },
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
      })
      .then(() => {
        // 1. 清除本地存储的token
        localStorage.removeItem('token');
        // 2. 跳转到登录页
        router.push({ name: 'Register' });
        ElMessage.success('注销成功');
      })
      .catch(() => {
        ElMessage.info('已取消注销');
      });
};
</script>

<template>
  <div style="background: #CCCCCC; height: 667px">
    <!-- 用户头像、昵称、微信号区域 -->
    <el-row style="padding-top: 30px; padding-bottom: 10px; background: white">
      <el-col :span="5">
        <!-- 头像显示 -->
        <img
            v-if="!userList.avatar"
            src="@/assets/icon/微信头像.svg"
            alt="默认头像"
            style="width: 60px; margin-left: 10px"
        />
        <el-image
            v-else
            :src="userList.avatar"
            style="width: 60px; margin-left: 10px"
            alt="用户头像"
        ></el-image>
      </el-col>
      <el-col :span="15">
        <div style="font-size: large; font-weight: bold;">{{ userList.username || '未知用户' }}</div>
        <div style="font-size: small">微信号：{{ userList.wechat_number || '未设置' }}</div>
      </el-col>
      <el-col :span="4">
        <div style="display: flex; flex-direction: column; align-items: center; gap: 8px;">
          <img src="@/assets/icon/二维码.svg" alt="二维码图标" style="width: 24px;" />
          <!-- 点击事件触发跳转（替代直接的router-link） -->
          <el-icon style="font-size: 17px; cursor: pointer;">
            <router-link to="PersonalDataVue">
              <ArrowRight />
            </router-link>
          </el-icon>
        </div>
      </el-col>
    </el-row>

    <!-- 服务区域 -->
    <div style="margin-top: 8px; margin-bottom: 8px">
      <el-row style="height: 50px; background: white;">
        <el-col :span="21">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 5px">
            <img src="@/assets/icon/微信支付.svg" alt="微信支付图标" style="width: 24px;" />
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">服务</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 10px">
            <el-icon style="font-size: 17px"><ArrowRight /></el-icon>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 其他功能区域（收藏、朋友圈等）保持不变 -->
    <div style="background: white;">
      <!-- 收藏 -->
      <el-row style="height: 50px; border-bottom: 1px solid #f0f0f0; margin-left: 5px;">
        <el-col :span="21">
          <div style="display: flex; align-items: center; height: 50px;">
            <img src="@/assets/icon/微信收藏.svg" alt="微信收藏图标" style="width: 24px;" />
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">收藏</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 10px">
            <el-icon style="font-size: 17px"><ArrowRight /></el-icon>
          </div>
        </el-col>
      </el-row>

      <!-- 朋友圈 -->
      <el-row style="height: 50px; border-bottom: 1px solid #f0f0f0; margin-left: 5px">
        <el-col :span="21">
          <div style="display: flex; align-items: center; height: 50px;">
            <img src="@/assets/icon/用户管理页面朋友圈.svg" alt="朋友圈图标" style="width: 24px;" />
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">朋友圈</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 10px">
           <router-link :to="{name: 'userMoments',query:{userId: userList.id}}" style="color: black">
            <el-icon style="font-size: 17px"><ArrowRight /></el-icon>
           </router-link>
          </div>
        </el-col>
      </el-row>

      <!-- 卡包 -->
      <el-row style="height: 50px; border-bottom: 1px solid #f0f0f0; margin-left: 5px">
        <el-col :span="21">
          <div style="display: flex; align-items: center; height: 50px;">
            <img src="@/assets/icon/微信卡包.svg" alt="微信卡包图标" style="width: 24px;" />
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">卡包</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 10px">
            <el-icon style="font-size: 17px"><ArrowRight /></el-icon>
          </div>
        </el-col>
      </el-row>

      <!-- 表情 -->
      <el-row style="height: 50px; margin-left: 5px">
        <el-col :span="21">
          <div style="display: flex; align-items: center; height: 50px;">
            <img src="@/assets/icon/微信表情.svg" alt="微信表情图标" style="width: 24px;" />
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">表情</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 10px">
            <el-icon style="font-size: 17px"><ArrowRight /></el-icon>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 设置 -->
    <div style="margin-top: 8px;">
      <el-row style="height: 50px; background: white;">
        <el-col :span="21">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 5px">
            <img src="@/assets/icon/微信设置.svg" alt="微信设置图标" style="width: 24px;" />
            <span style="margin-left: 12px; font-size: 17px; font-weight: bold;">设置</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div style="display: flex; align-items: center; height: 50px; margin-left: 9px">
            <el-icon style="font-size: 17px"><ArrowRight /></el-icon>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 退出登录 -->
    <div style="margin-top: 8px;">
      <el-row style="height: 50px; background: white;">
        <el-col :span="24">
          <div
              style="height: 50px; display: flex; align-items: center; justify-content: center; cursor: pointer;"
              @click="handleLogout"
          >
            <span style="font-size: 17px; font-weight: bold; color: red;">退出登录</span>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 注销账号 -->
    <div style="margin-top: 8px;">
      <el-row style="height: 50px; background: white;">
        <el-col :span="24">
          <div style="height: 50px; display: flex; align-items: center; justify-content: center; cursor: pointer;"
               @click="write">
            <span style="font-size: 17px; font-weight: bold; color: red; cursor: pointer;">注销此账号</span>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
  <BottomNavigation/>
</template>

<style scoped>

</style>